package com.weifly.weistock.record.base;

import com.weifly.weistock.record.base.domain.RecordPair;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 存储服务基类
 *
 * @author weifly
 * @since 2020/01/16
 */
public class AbstractStoreService {

    private Logger log = LoggerFactory.getLogger(AbstractStoreService.class);

    protected String configPath; // 存储路径

    /**
     * 设置配置文件路径
     */
    public void setConfigPath(String configPath){
        this.configPath = configPath;
    }

    protected File getStoreFile(){
        File storeFolder = new File(this.configPath);
        if(!storeFolder.exists()){
            storeFolder.mkdirs();
            log.info("创建目录: " + storeFolder.getAbsolutePath());
        }
        return storeFolder;
    }

    protected String makePairAttr(List<RecordPair> pairList, int tradeNumber){
        if(pairList==null || pairList.isEmpty()){
            return null;
        }
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<pairList.size();i++){
            RecordPair pair = pairList.get(i);
            // 输出index
            if(pair.getNumber()==tradeNumber){
                sb.append(pair.getIndex());
            }else{
                sb.append(pair.getIndex());
                if(pair.getNumber()>1){
                    sb.append("(").append(pair.getNumber()).append(")");
                }
            }
            // 输出分隔符
            if(i<pairList.size()-1){
                sb.append(",");
            }
        }
        return sb.toString();
    }

    protected List<RecordPair> parsePairAttr(String pairAttr, int tradeNumber){
        if(StringUtils.isBlank(pairAttr)){
            return null;
        }
        List<RecordPair> pairList = new ArrayList<>();
        String[] parts = pairAttr.split(",");
        for(String p : parts){
            RecordPair pair = new RecordPair();
            if(p.indexOf("(")==-1){
                pair.setIndex(Integer.parseInt(p));
                pair.setNumber(tradeNumber);
            }else{
                int startIdx = p.indexOf("(");
                int endIdx = p.indexOf(")");
                pair.setIndex(Integer.parseInt(p.substring(0, startIdx)));
                pair.setNumber(Integer.parseInt(p.substring(startIdx+1, endIdx)));
            }
            pairList.add(pair);
        }
        return pairList;
    }
}
